#!/usr/bin/env bash

# Execute by: bash xxx.sh or bash zzz/yyy/xxx.sh or ./xxx.sh or ./zzz/yyy/xxx.sh source xxx.sh
REALPATH=$(realpath ${BASH_SOURCE[0]})
SCRIPT_DIR=$(cd $(dirname ${REALPATH}) && pwd)
WORK_DIR=$(cd $(dirname ${REALPATH})/.. && pwd)
echo "BASH_SOURCE=${BASH_SOURCE}, REALPATH=${REALPATH}, SCRIPT_DIR=${SCRIPT_DIR}, WORK_DIR=${WORK_DIR}"
cd ${WORK_DIR}

echo "Start Redis server, WORK_DIR:${WORK_DIR}"

# Get the metadata of machine.
if [[ -f ${WORK_DIR}/containers/data/config/.env ]]; then source ${WORK_DIR}/containers/data/config/.env; fi
echo "LoadEnv CLOUD=$CLOUD REGION=$REGION, SOURCE=$SOURCE"

REDIS_PARAMS="${WORK_DIR}/containers/conf/redis.conf --daemonize yes"
if [[ ! -z $REDIS_PASSWORD ]]; then REDIS_PARAMS="${REDIS_PARAMS} --requirepass $REDIS_PASSWORD"; fi
if [[ ! -z $REDIS_PORT ]]; then REDIS_PARAMS="${REDIS_PARAMS} --port $REDIS_PORT"; fi

mkdir -p /data/redis
REDIS_PARAMS="${REDIS_PARAMS} --dir /data/redis"
echo "Run redis-server $REDIS_PARAMS"

mkdir -p /var/run/redis &&
redis-server $REDIS_PARAMS &&
REDIS_PID_FILE="/var/run/redis/redis-server.pid"
if [[ $? -ne 0 ]]; then echo "Start redis failed"; exit 1; fi

for ((i=0; i<10; i++)); do
if [[ -f $REDIS_PID_FILE ]]; then
  ps -p `cat $REDIS_PID_FILE` 1>/dev/null 2>/dev/null &&
  echo "Redis server started, pid=`cat $REDIS_PID_FILE`" &&
  break
fi
sleep 0.3
done

ps -p `cat $REDIS_PID_FILE` 1>/dev/null 2>/dev/null
if [[ $? -ne 0 ]]; then echo "Check redis failed"; exit 1; fi

